// $Id$
package de.servicezombie.pub.r1;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
 * Base wrapper class to serialize json or xml data:
 * <pre>
 *   response: {
 *     sys: { 
 *       returnCode: "OK", 
 *       debugText: "foo" // optional 
 *     }
 *     messages { // optional
 *       errors [
 *         message: {
 *           key: "label.foo.bar"
 *         }
 *       ],
 *     }
 *     
 *     any-data: { ... } // optional
 *   }
 *   
 * </pre>
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "sys", "messages", "body", "version" }, namespace = XmlNamespaces.SERVICEZOMBIE_COMMON)
@XmlRootElement(name = "response")
public class CommonRestResponse<T> {
	
	@XmlElement(required = true)
	private Sys sys = new Sys();

	@XmlElement(required = true)
	private MessageContainer messages = new MessageContainer();

	/**
	 * domain objects returned by this response may set an optional 
	 * version identifier. 
	 */
	@XmlElement(required = false)
	private String version = null;

	@XmlAnyElement(lax = true)
	private T body = null;

	public void setVersion(String version) {
		this.version = version;
	}

	public String getVersion() {
		return version;
	}

	public T getBody() {
		return body;
	}

	public void setBody(T bean) {
		body = bean;
	}

	public void reset() {
		setBody(null);
		messages.clearAll();
		sys = new Sys();
	}

	public Sys getSys() {
		assert sys != null;
		return sys;
	}

	public MessageContainer getMessages() {
		return messages;
	}

	@Override
	public String toString() {
		return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
				.append("sys", sys)
				.append("messages", messages)
				.append("body", body)
				.toString();
	}

}
